/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-undef */
const md5 = require('js-md5')
import { message } from 'antd'
const storage = {
  set: (key, value = null) => {
    if (key) {
      localStorage.setItem(key, JSON.stringify(value))
      return
    }
    return 'key 不能为空'
  },
  get: (key) => {
    if (key) {
      return JSON.parse(localStorage.getItem(key)) 
    }
    return 'key 不能为空'
  },
  remove: (key) => {
    if (key) {
      localStorage.remove(key)
    }
  }
}

message.config({
  top: 50,
  maxCount: 1,
})

export const successMsg = (text, duration = 2) => {
  message.success(text, duration)
}

export const warnMsg = (text, duration = 2) => {
  message.warning(text, duration)
}

export const errorMsg = (text, duration = 2) => {
  message.error(text, duration)
}

export const infoMsg = (text, duration = 2) => {
  message.info(text, duration)
}

/*
* 将时间戳转化为 “几周前” 的形式
*/
const getAgoAt = (stamptime) => {
  stamptime = Math.round(new Date(stamptime) / 1000)
  const currentTime = Math.round(new Date() / 1000)
  const diff = currentTime - stamptime
  let agoAt = '刚刚'
  const timePoints = [
    { value: 60 * 60 * 24 * 365, suffix: '年前', max: 2 },
    { value: 60 * 60 * 24 * 30,  suffix: '月前', max: 11 },
    { value: 60 * 60 * 24 * 7,   suffix: '周前', max: 4 },
    { value: 60 * 60 * 24,       suffix: '天前', max: 6 },
    { value: 60 * 60,            suffix: '小时前', max: 23 },
    { value: 60 * 10,            suffix: '0分钟前', max: 5 }
  ]

  for (let i = 0; i < timePoints.length; i++) {
    const point = timePoints[i]
    const mode = Math.floor(diff / point.value)
    if (mode > 1) {
      agoAt = Math.min(mode, point.max) + point.suffix
      break
    }
  }
  return agoAt
}
const addZero = (date) => date < 10 ? `0${date}` : date
const transformTime = (date, type = 'YMDHS') => {
  const jsonDate = new Date(date).toJSON()
  const _date = new Date(new Date(jsonDate) + (8 * 3600 * 1000))
  switch (type) {
  case 'YMDHS': 
    return `${_date.getFullYear()}-${addZero(_date.getMonth() + 1)}-${addZero(_date.getDate())} ${addZero(_date.getHours())}:${addZero(_date.getMinutes())}:${addZero(_date.getSeconds())}`
  case 'YMD':
    return `${_date.getFullYear()}-${addZero(_date.getMonth() + 1)}-${addZero(_date.getDate())}`
  case 'YM':
    return `${_date.getFullYear()}-${addZero(_date.getMonth() + 1)}`
  default:
  }
  
}
// xxxx-xx-xx --> xxxx年xx月xx日
const dateConversion = (date) => {
  if (date.length > 10) {
    const _date = date.split(/[-: ]/u)
    return `${_date[0]}年${_date[1]}月${_date[2]}日 ${_date[3]}:${_date[4]}:${_date[5]}`  
  } 
  const _date = date.split(/[- ]/u)
  return `${_date[0]}年${_date[1]}月${_date[2]}日` 
}

// 生成 oss 上传目录
const createUploadCatalogue = (type, fileName) => {
  if (!['image', 'file', 'video'].includes(type)) return Promise.reject('类型错误')

  let date = new Date() // 当前时间

  let _index = fileName.lastIndexOf('.')
  if (_index === -1) return Promise.reject('文件后缀名异常')

  let _fileName = fileName.slice(0, _index) // 文件名
  let suffix = fileName.substring(_index) // 文件后缀
  
  const zeroFill = (i) => {
    if (i >= 0 && i <= 9) return `0${i}`
    return i
  }
  const getMd5 = (str) => {
    md5(str)
    let hash = md5.create()
    hash.update(str)
    return hash.hex()
  }
  
  // 文件名加密规则：文件名 + 时间戳（到毫秒）+ 1000 随机数
  let md5FileName = getMd5(`${_fileName}${date.valueOf()}${Math.random() * 1000}`)
  let year = date.getFullYear()
  let month = zeroFill(date.getMonth() + 1) // 月
  let day = zeroFill(date.getDate()) // 日

  return `${type}/${year}${month}${day}/${md5FileName}${suffix}`
}

export {
  storage,
  getAgoAt,
  dateConversion,
  transformTime,
  createUploadCatalogue
}